//
//  UILabel+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 2020/6/13.
//  Copyright © 2020 scoresdata.net. All rights reserved.
//

import UIKit

/*
 点击标签的区域文字事件
 使用方法：
 @IBAction func tapLabel(gesture: UITapGestureRecognizer) {
 if gesture.didTapAttributedTextInLabel(myLabel, inRange: targetRange1) {
     print("Tapped targetRange1")
 } else if gesture.didTapAttributedTextInLabel(myLabel, inRange: targetRange2) {
     print("Tapped targetRange2")
 } else {
     print("Tapped none")
 }}
 **/
extension UITapGestureRecognizer {
    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
        // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)
        let textStorage = NSTextStorage(attributedString: label.attributedText!)

        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines
        let labelSize = label.bounds.size
        textContainer.size = labelSize
        
        // Find the tapped character location and compare it to the specified range
        let locationOfTouchInLabel = self.location(in: label)
        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y:locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in:textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

        return NSLocationInRange(indexOfCharacter, targetRange)
    }
}


extension UILabel {
    ///快捷生成UILabel
    convenience init(_ fontSize:CGFloat,
                     weight:UIFont.Weight = .regular,
                     textColor:UIColor = .black,
                     text:String? = nil,
                     numberOfLines:Int = 1,
                     align:NSTextAlignment = .left) {
        self.init()
        self.textColor = textColor
        self.font = UIFont.systemFont(ofSize:fontSize,weight:weight)
        self.text = text
        self.numberOfLines = numberOfLines
        self.textAlignment = align
    }
    
    /// 一行生成UILabel对象
    /// - Parameters:
    ///   - frame: <#frame description#>
    ///   - text: <#text description#>
    ///   - textColor: <#textColor description#>
    ///   - fontSize: <#fontSize description#>
    ///   - weight: <#weight description#>
    ///   - align: <#align description#>
    ///   - lines: <#lines description#>
    ///   - breakMode: <#breakMode description#>
    convenience init(frame:CGRect = .zero, text:String? = nil, textColor:UIColor = .black, fontSize:CGFloat = 12, weight:UIFont.Weight = .regular, bgColor:UIColor = .clear, align:NSTextAlignment = .left, lines:NSInteger = 1, breakMode:NSLineBreakMode = .byTruncatingTail) {
        self.init()
        self.frame = frame
        self.backgroundColor = bgColor
        self.text = text
        self.textColor = textColor
        self.textAlignment = align
        self.font = UIFont.systemFont(ofSize:fontSize,weight:weight)
        self.numberOfLines = lines
        self.lineBreakMode = breakMode
    }
    convenience init(text:String? = nil, textColor:UIColor = .black, fontSize:CGFloat = 12, weight:UIFont.Weight = .regular, bgColor:UIColor = .clear, align:NSTextAlignment = .left, lines:NSInteger = 1, breakMode:NSLineBreakMode = .byTruncatingTail) {
        self.init()
        self.backgroundColor = bgColor
        self.text = text
        self.textColor = textColor
        self.textAlignment = align
        self.font = UIFont.systemFont(ofSize:fontSize,weight:weight)
        self.numberOfLines = lines
        self.lineBreakMode = breakMode
    }
    
    var unnull_font : UIFont {
        return self.font ?? UIFont.systemFont(ofSize: 16)
    }
    
    ///调用此方法之前，要保证已经有了text
    func setLineSpacingAfterSetText(_ lineSpacing:CGFloat) {
        let t = text ?? ""
        let paraStyle = NSMutableParagraphStyle()
        paraStyle.lineSpacing = lineSpacing
        paraStyle.alignment = textAlignment
        var dic = [NSAttributedString.Key.paragraphStyle:paraStyle] as [NSAttributedString.Key:Any]
        dic[NSAttributedString.Key.font] = font
        attributedText = NSAttributedString(string:t,attributes:dic)
    }
    
    /// 设置行间距
    func setTextAndLineSpacing(text:String?,lineSpacing:CGFloat) {
        self.text = text ?? ""
        self.setLineSpacingAfterSetText(lineSpacing)
    }
    
    func richText(titles:[String],
                  fontSizes:[CGFloat] = [16],
                  weights:[UIFont.Weight] = [UIFont.Weight.regular],
                  colors:[UIColor] = [UIColor.black],
                  lineSpac:CGFloat = 0) {
        attributedText = NSAttributedString.richText(titles: titles,
                                                     fontSizes: fontSizes,
                                                     weights: weights,
                                                     colors: colors,
                                                     lineSpac: lineSpac,
                                                     alignment: textAlignment)
    }
}
